package com.empire.module.member.service.locationlast;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.empire.framework.common.util.date.LocalDateTimeUtils;
import com.empire.module.member.dal.mysql.location.LocationMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.empire.module.member.controller.admin.locationlast.vo.*;
import com.empire.module.member.dal.dataobject.locationlast.LocationLastDO;
import com.empire.framework.common.pojo.PageResult;
import com.empire.framework.common.util.object.BeanUtils;

import com.empire.module.member.dal.mysql.locationlast.LocationLastMapper;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import static com.empire.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.empire.module.member.enums.ErrorCodeConstants.*;

/**
 * 定位信息 Service 实现类
 *
 * @author 主席大人
 */
@Service
@Validated
public class LocationLastServiceImpl extends ServiceImpl<LocationLastMapper, LocationLastDO> implements LocationLastService {

    @Resource
    private LocationLastMapper locationLastMapper;
    @Resource
    private LocationMapper locationMapper;

    @Override
    public Long createLocationLast(LocationLastSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null || createReqVO.getPersonId() == null) {
            throw new IllegalArgumentException("请求参数或人员ID不能为空");
        }

        // 转换为DO对象
        LocationLastDO locationLastDO = BeanUtils.toBean(createReqVO, LocationLastDO.class);
        // 查询现有记录
        LocationLastDO existingLocationLastDO = locationLastMapper.selectById(createReqVO.getPersonId());

        // 提取：获取常出现地址及次数的通用方法
        Map<String, Object> frequentAddressInfo = getFrequentAddressInfo(createReqVO.getPersonId());

        // 处理常出现地址信息
        String frequentAddress = null;
        int appearanceCount = 0;
        if (frequentAddressInfo != null) {
            frequentAddress = (String) frequentAddressInfo.get("address");
            appearanceCount = ((Number) frequentAddressInfo.
                    getOrDefault("appearance_count", 0)).intValue();
        }

        // 新增逻辑
        if (existingLocationLastDO == null) {
            locationLastDO.setId(createReqVO.getPersonId());
            locationLastDO.setCreateTime(LocalDateTime.now());
            locationLastDO.setUpdateTime(LocalDateTime.now());
            // 设置常出现地址（优先使用统计结果，无统计结果则使用当前地址）
            locationLastDO.setFrequentAddress(frequentAddress != null ? frequentAddress : createReqVO.getAddress());
            locationLastDO.setAppearanceCount(appearanceCount);
            // 设置初始定位信息
            locationLastDO.setLocationTime(createReqVO.getLocationTime());
            locationLastDO.setLat(createReqVO.getLat());
            locationLastDO.setLng(createReqVO.getLng());
            locationLastDO.setAddress(createReqVO.getAddress());

            locationLastMapper.insert(locationLastDO);
            return locationLastDO.getId();
        }

        // 更新逻辑
        // 1. 先更新常出现地址（无论定位时间是否更新，都同步最新统计结果）
        existingLocationLastDO.setFrequentAddress(frequentAddress);
        existingLocationLastDO.setAppearanceCount(appearanceCount);
        existingLocationLastDO.setUpdateTime(LocalDateTime.now());

        // 2. 若当前定位时间更新，则同步最新定位信息
        LocalDateTime newLocationTime = createReqVO.getLocationTime();
        if (newLocationTime != null && LocalDateTimeUtils.date1BeforeDate2(
                existingLocationLastDO.getLocationTime(), newLocationTime)) {
            existingLocationLastDO.setLocationTime(newLocationTime);
            existingLocationLastDO.setLat(createReqVO.getLat());
            existingLocationLastDO.setLng(createReqVO.getLng());
            existingLocationLastDO.setAddress(createReqVO.getAddress());
        }

        locationLastMapper.updateById(existingLocationLastDO);
        return existingLocationLastDO.getId();
    }

    /**
     * 获取人员常出现地址及出现次数
     */
    private Map<String, Object> getFrequentAddressInfo(Long personId) {
        List<Map<String, Object>> frequentMap = locationMapper.selectMostFrequentAddress(personId, 1);
        return frequentMap != null && !frequentMap.isEmpty() ? frequentMap.getFirst() : null;
    }

    @Override
    public void updateLocationLast(LocationLastSaveReqVO updateReqVO) {
        // 校验存在
        validateLocationLastExists(updateReqVO.getId());
        // 更新
        LocationLastDO updateObj = BeanUtils.toBean(updateReqVO, LocationLastDO.class);
        locationLastMapper.updateById(updateObj);
    }

    @Override
    public void deleteLocationLast(Long id) {
        // 校验存在
        validateLocationLastExists(id);
        // 删除
        locationLastMapper.deleteById(id);
    }

    private void validateLocationLastExists(Long id) {
        if (locationLastMapper.selectById(id) == null) {
            throw exception(LOCATION_LAST_NOT_EXISTS);
        }
    }

    @Override
    public LocationLastDO getLocationLast(Long id) {
        return locationLastMapper.selectById(id);
    }

    @Override
    public PageResult<LocationLastDO> getLocationLastPage(LocationLastPageReqVO pageReqVO) {
        return locationLastMapper.selectPage(pageReqVO);
    }

}